package com.honyelchak.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.honyelchak.shortlink.admin.dao.entity.GroupDO;
import com.honyelchak.shortlink.admin.dao.mapper.GroupMapper;
import com.honyelchak.shortlink.admin.dto.req.GroupDeleteReqDTO;
import com.honyelchak.shortlink.admin.dto.req.GroupSortReqDTO;
import com.honyelchak.shortlink.admin.dto.req.GroupUpdateReqDTO;
import com.honyelchak.shortlink.admin.dto.resp.GroupRespDTO;
import com.honyelchak.shortlink.admin.remote.ShortLinkRemoteService;
import com.honyelchak.shortlink.admin.remote.resp.ShortLinkCountQueryRespDTO;
import com.honyelchak.shortlink.admin.service.GroupService;
import com.honyelchak.shortlink.admin.util.RandomGenerator;
import com.honyelchak.shortlink.base.common.constant.BaseConstant;
import com.honyelchak.shortlink.base.common.constant.GroupConstant;
import com.honyelchak.shortlink.base.common.convention.exception.ClientException;
import com.honyelchak.shortlink.base.common.convention.result.Result;
import com.honyelchak.shortlink.base.common.user.UserContext;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {};

    @Override
    public void saveGroup(String groupName) {
        saveGroup(UserContext.getUsername(), groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        String gid = null;
        do {
            gid = RandomGenerator.generateRandom();
        } while(hasGid(username, gid));

        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .name(groupName)
                .username(username)
                .sortOrder(GroupConstant.DEFAULT_SORT_ORDER)
                .build();
        baseMapper.insert(groupDO);
    }

    @Override
    public List<GroupRespDTO> listGroup() {
        if (Optional.ofNullable(UserContext.getUsername()).isEmpty()) {
            // TODO 用户未登录，跳转到登录页
            throw new ClientException("用户未登录！");
        }
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, BaseConstant.NOT_DELETED)
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
        List<String> gids = groupDOList.stream().map(GroupDO::getGid).collect(Collectors.toList());
        Result<List<ShortLinkCountQueryRespDTO>> listResult = shortLinkRemoteService.listGroupShortLinkCount(gids);
        Map<String, List<ShortLinkCountQueryRespDTO>> gid2CountMap = listResult.getData().stream().collect(Collectors.groupingBy(ShortLinkCountQueryRespDTO::getGid));

        List<GroupRespDTO> shortLinkgroupRespDTOList = BeanUtil.copyToList(groupDOList, GroupRespDTO.class);

        shortLinkgroupRespDTOList.forEach(each -> {
            Optional<List<ShortLinkCountQueryRespDTO>> shortLinkCountQueryRespDTOS = Optional.ofNullable(gid2CountMap.get(each.getGid()));
            if (shortLinkCountQueryRespDTOS.isEmpty() || shortLinkCountQueryRespDTOS.get().isEmpty()) {
                each.setShortLinkCount(0);
            } else {
                Optional<ShortLinkCountQueryRespDTO> first = shortLinkCountQueryRespDTOS.get().stream().findFirst();
                each.setShortLinkCount(first.get().getShortLinkCount());
            }
        });

        return shortLinkgroupRespDTOList;
    }

    @Override
    public void delete(GroupDeleteReqDTO reqDTO) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, reqDTO.getGid())
                .eq(GroupDO::getDelFlag, BaseConstant.NOT_DELETED);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(BaseConstant.DELETED);
        baseMapper.update(groupDO, queryWrapper);
    }

    @Override
    public void update(GroupUpdateReqDTO reqDTO) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, reqDTO.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername());
        GroupDO groupDO = GroupDO.builder().name(reqDTO.getName()).build();
        baseMapper.update(groupDO, queryWrapper);
    }

    @Override
    public void sort(List<GroupSortReqDTO> reqDTO) {
        reqDTO.forEach((e) -> {
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getGid, e.getGid())
                    .eq(GroupDO::getUsername, UserContext.getUsername());
            GroupDO groupDO = GroupDO.builder().sortOrder(e.getSortOrder()).build();
            baseMapper.update(groupDO, queryWrapper);
        });
    }

    private boolean hasGid(String username, String gid){
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);
        return groupDO != null;
    }
}
